package com.gkj.blog.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gkj.blog.business.enums.UserTypeEnum;
import com.gkj.blog.business.service.UserService;
import com.gkj.blog.business.vo.condition.UserConditionVO;
import com.gkj.blog.business.vo.entity.User;
import com.gkj.blog.framework.holder.RequestHolder;
import com.gkj.blog.framework.object.AbstractServiceImpl;
import com.gkj.blog.persistence.mapper.SysUserMapper;
import com.gkj.blog.persistence.po.SysUser;
import com.gkj.blog.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl extends AbstractServiceImpl<User,SysUser> implements UserService {
    SysUserMapper sysUserMapper;

    @Autowired
    public void setSysUserMapper(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
        setBaseMapper(sysUserMapper);
    }

    @Override
    public User getUserByUsername(String username) {
        SysUser sysUser = sysUserMapper.getUserByUserName(username);
        if (sysUser==null){
            return null;
        }else {
            return new User(sysUser);
        }
    }

    @Override
    public boolean updateUserLastLoginInfo(User user) {
        if (user != null) {
            user.setLoginCount(user.getLoginCount() + 1);
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(IpUtil.getRealIp(RequestHolder.getRequest()));
            user.setPassword(null);
        }
        return  baseMapper.updateByPrimaryKeySelective(user.getAbstractDo())>0;
    }

    @Override
    public PageInfo<User> findPageBreakByCondition(UserConditionVO vo) {
        PageHelper.startPage(vo.getPageNumber(), vo.getPageSize());
        List<SysUser> sysUsers = sysUserMapper.findPageBreakByCondition(vo);
        if (CollectionUtils.isEmpty(sysUsers)) {
            return null;
        }
        List<User> users = new ArrayList<>();
        for (SysUser su : sysUsers) {
            users.add(new User(su));
        }
        PageInfo bean = new PageInfo<SysUser>(sysUsers);
        bean.setList(users);
        return bean;
    }
}
